import { ref } from 'vue'

/**
 * 节流函数，限制函数执行频率
 * @param fn 要执行的函数
 * @param delay 延迟时间（毫秒），默认300ms
 * @returns 节流后的函数
 */
export function useThrottle<T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300
): (...args: Parameters<T>) => Promise<ReturnType<T>> {
  const isThrottled = ref(false)
  
  return async (...args: Parameters<T>): Promise<ReturnType<T>> => {
    if (isThrottled.value) {
      return Promise.reject(new Error('函数执行被节流'))
    }
    
    try {
      isThrottled.value = true
      const result = await fn(...args)
      
      setTimeout(() => {
        isThrottled.value = false
      }, delay)
      
      return result
    } catch (error) {
      isThrottled.value = false
      throw error
    }
  }
}

export default useThrottle
